Skip to main content

Kruskal's Algorithm

1. What is Kruskal's Algorithm?​

Kruskal's Algorithm is used to find the minimum spanning tree (MST) of a connected, undirected graph. It greedily selects edges with the lowest weight that do not form cycles, gradually building the MST.

2. Algorithm for Kruskal's Algorithm​

  1. Sort all the edges of the graph in non-decreasing order of their weight.
  2. Initialize an empty set to store the MST.
  3. Iterate through the sorted edges, adding each edge to the MST if it doesn't create a cycle.
  4. Repeat until all vertices are connected or the MST contains (Vβˆ’1)(V-1) edges, where VV is the number of vertices.

3. How Does Kruskal's Algorithm Work?​

  • Kruskal's Algorithm greedily selects edges with the lowest weight that do not form cycles, gradually building the MST.

4. Problem Description​

Given a weighted, connected graph, Kruskal's Algorithm aims to find the minimum spanning tree (MST) of the graph.

5. Examples​

Example graph:

      0    1    2    3
--------------------
0 | 0 2 0 6
1 | 2 0 3 8
2 | 0 3 0 0
3 | 6 8 0 0

6. Constraints​

  • The graph must be connected and undirected.
  • The weights of the edges can be positive or negative.

7. Implementation​

Kruskal's Algorithm​

def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])

def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)

if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1

def kruskal(graph):
V = len(graph)
result = []
i = 0
e = 0
graph = sorted(graph, key=lambda item: item[2])
parent = [i for i in range(V)]
rank = [0] * V

while e < V - 1:
u, v, w = graph[i]
i = i + 1
x = find(parent, u)
y = find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
union(parent, rank, x, y)

return result

8. Complexity Analysis​

  • Time Complexity: O(ElogE)O(E log E) for sorting the edges, where EE is the number of edges, and O(ElogV)O(E log V) for finding the minimum spanning tree, where VV is the number of vertices.
  • Space Complexity: O(V+E)O(V + E), for storing the edges and disjoint set.

9. Advantages and Disadvantages​

Advantages:​

  • Finds the minimum spanning tree of a graph efficiently.
  • Works well with both dense and sparse graphs.

Disadvantages:​

  • Requires sorting of edges, which can be computationally expensive.
  • Not suitable for graphs with negative edge weights.

10. References​